<template>
    <div>
    <search-bar @onSearch="onSearch"></search-bar>
    <div class="btns">
    <!-- 单个导入 -->
    <el-button type="primary" @click="$router.push('/itemAdd')">单个导入</el-button>
    <el-upload action="#"
     accept=".xlsx, .xls"
     :before-upload="readExcel">
     <!-- 批量导入 -->
        <el-button type="success" style="margin: 0 10px;">批量导入</el-button>
      </el-upload>
      <!-- 下载模板 -->
    <el-button type="danger" @click="exportItemTpl()">下载模板</el-button>
    </div>
      <el-table :data="items" style="width: 100%">
        <el-table-column prop="itemName" label="商品名字" width="180" />
        <el-table-column prop="price" label="商品价格" width="180" />
        <el-table-column prop="desc" label="商品描述" width="180">
          <template #default="{row}">
            <el-tooltip  effect="dark" placement="top">
            <template #content>
              <div class="smallbtn">
              <!-- 鼠标放入商品描述时，展示详情描述 -->
                {{ row.desc }}
              </div>
            </template>
            <!-- 只展示部分的商品描述 -->
              <div>{{ row.desc.substr(0,21) + '...' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="sale" label="销量" >
          <template #default="{ row }">
            <el-tag> {{ row.sale }}</el-tag>
          </template>
        </el-table-column>
        <!-- 上下架 -->
        <el-table-column prop="onsale" label="上下架">
          <template #default="{ row }">
          <div>
          <el-switch v-model="row.onsale" inline-prompt active-text="上架"
          @change="switchSaleState(row.id, row.onsale)"
          inactive-text="下架"></el-switch>
          </div>
          </template>
        </el-table-column>
        <el-table-column prop="createAt" label="上架时间" />
      <el-table-column prop="thumb" label="封面图片">
        <template #default="{ row }">
          <div>
            <el-image style="width: 50px; height: 50px"
            :src="row.thumb"
            :zoom-rate="1.2"
            :preview-src-list="row.imgLists"
            preview-teleported
            fit="cover" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div>
          <!-- 编辑 -->
            <el-button @click="enterUpdate(row.id)" type="primary">编辑</el-button>
            <!-- 删除 -->
            <el-button type="danger" @click="delItem(row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
      </el-table>
      <!-- 底部的商品分页 -->
      <div class="example-pagination-block">
        <el-pagination layout="prev, pager, next, jumper, sizes"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="page" />
      </div>
    </div>
</template>

<script>
import { fetchItems, addItems, delItem } from '@/api/itemLists'
import { updateItem } from '@/api/itemUpdate'
import SearchBar from '@c/SearchBar.vue'
import { read, utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'itemLists',
  data () {
    return {
      searchParams: { // 搜索参数
        key: '',
        start: '',
        end: ''
      },
      page: 1, // 页码
      pageSize: 10, // 每页商品数量
      items: [], // 商品列表数据
      total: 0 // 商品总数
    }
  },
  methods: {
    delItem (id) {
      // 删除指定id的商品
      this.$confirm('确定要删除吗？', '删除').then(() => {
        delItem(id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.$router.go(0)
          }
        })
      })
    },
    enterUpdate (id) {
      // 跳转到编辑商品页面,传递id
      this.$router.push({
        path: '/itemUpdate',
        query: {
          id
        }
      })
    },
    readExcel (file) {
      // 读取上传的excel表格
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      fd.onload = () => {
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        const _data = data.map(item => {
          return {
            itemName: item.商品名,
            price: item.商品价格,
            desc: item.商品描述
          }
        })
        // 请求批量添加商品的接口
        addItems({
          items: _data
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.$router.go(0) // 刷新回归初始值
          }
        })
      }
      return false
    },
    exportItemTpl () {
      // 导出商品列表
      const data = [
        {
          商品名: '商品1',
          商品价格: 10,
          商品描述: '这是描述'
        }
      ]
      const ws = utils.json_to_sheet(data)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '商品excel模板.xlsx')
    },
    onSearch (searchParams) {
      // 更新searchParams并且重新调用fetchItems获取商品列表
      this.searchParams = searchParams
      this.fetchItems()
    },
    switchSaleState (id, onsale) {
      // 切换上下架状态
      updateItem({
        id,
        onsale
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            onClose: () => {
              this.$router.go(0)
            }
          })
        }
      })
    },
    fetchItems () {
      // 获取商品列表数据 并且更新item和total
      fetchItems({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        console.log(res.data)
        if (res.data.code === 200) {
          this.items = res.data.data.lists
          this.total = res.data.data.total
        }
      })
    }
  },
  watch: {
    page () {
      this.fetchItems()
    },
    pageSize () {
      this.fetchItems()
    }
  },
  created () {
    this.fetchItems()
  },
  components: {
    SearchBar
  }
}
</script>

<style lang="scss" scoped>
.btns{
  display: flex;
}
.smallbtn{
  width: 200px;
}

.example-pagination-block{
  margin-top: 20px;
  .el-popper.is-customized {
  width: 200px;
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}
.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
}
</style>
